package wallet

import (
	"bytes"
	"context"
	"database/sql"
	"errors"
	"fmt"
	v1 "hotgo/api/api/wallet/v1"
	"hotgo/internal/consts"
	"hotgo/internal/dao"
	"hotgo/internal/library/contexts"
	"hotgo/internal/library/hgorm"
	"hotgo/internal/library/location"
	"hotgo/internal/library/payment"
	"hotgo/internal/library/response"
	"hotgo/internal/library/wechat"
	"hotgo/internal/model"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/adminin"
	"hotgo/internal/model/input/payin"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/joinpay/utils"
	"strconv"
	"strings"
	"time"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/zeromicro/go-zero/core/jsonx"
)

func (c *ControllerV1) BankCardInfo(ctx context.Context, req *v1.BankCardInfoReq) (res *v1.BankCardInfoRes, err error) {
	res = new(v1.BankCardInfoRes)
	r, err := wechat.GetBankInfo(ctx, req.BankCardNo)
	if err != nil {
		return nil, err
	}
	res = &v1.BankCardInfoRes{
		GetBankByNumResp: r,
	}
	if res.Errcode != 0 {
		switch res.Errcode {
		case 9710001:
			return nil, gerror.New("无法获取银行卡信息,请检查银行卡号是否正确或更换银行卡")
		default:
			return nil, gerror.New("无法获取银行卡信息,请稍后再试")
		}
	}
	if res.Data != nil && len(res.Data) > 0 {
		bankIcon := &entity.BankIcon{}
		err = dao.BankIcon.Ctx(ctx).WhereLike(dao.BankIcon.Columns().Name, "%"+res.Data[0].BankName+"%").Scan(bankIcon)
		if err != nil {
			return nil, gerror.Wrap(err, "获取银行卡信息失败")
		}
		if bankIcon.Icon != "" {
			res.Data[0].BankIcon = bankIcon.Icon
		} else {
			res.Data[0].BankIcon = "https://imgs.ynz666.com/xiuxianba/2025-04-21/d9c7yhojkjh4sqfjti.png"
		}
	}
	return res, nil
}

func (c *ControllerV1) StoreBankCardBind(ctx context.Context, req *v1.StoreBankCardBindReq) (res *v1.StoreBankCardBindRes, err error) {
	res = new(v1.StoreBankCardBindRes)
	err = service.SysWalletStoreBank().APIEditCard(ctx, &req.WalletStoreBankAPIEditInp)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func (c *ControllerV1) StoreBankCardBindSmsSend(ctx context.Context, req *v1.StoreBankCardBindSmsSendReq) (res *v1.StoreBankCardBindSmsSendRes, err error) {
	if err = service.SysSmsLog().SendCode(ctx, &sysin.SendCodeInp{
		Event:  consts.SmsTemplateLogin,
		Mobile: req.Mobile,
	}); err != nil {
		return nil, err
	}
	res = new(v1.StoreBankCardBindSmsSendRes)
	return
}

func (c *ControllerV1) StoreWalletInfo(ctx context.Context, req *v1.StoreWalletInfoReq) (res *v1.StoreWalletInfoRes, err error) {
	flag, err := service.SysStoreMember().StorePermission(ctx, &sysin.StorePermissionInp{
		StoreId: req.StoreId,
		IsAdmin: 1,
	})

	res = new(v1.StoreWalletInfoRes)
	if err != nil {
		return nil, gerror.New("商户权限验证失败")
	}
	if !flag {
		return nil, gerror.New("无权限")
	}

	user, err := service.AdminMember().GetById(ctx, &adminin.GetByIdInp{Id: contexts.GetUserId(ctx)})
	if err != nil {
		return nil, gerror.New("获取用户信息失败")
	}

	res.Mobile = user.Mobile

	res.WalletStoreBank, err = service.SysWalletStoreBank().GetByStoreId(ctx, req.StoreId)
	if res.WalletStoreBank != nil && res.WalletStoreBank.BankName != "" {
		bankIcon := &entity.BankIcon{}
		err = dao.BankIcon.Ctx(ctx).WhereLike(dao.BankIcon.Columns().Name, "%"+res.WalletStoreBank.BankName+"%").Scan(bankIcon)
		if err != nil && !gerror.Is(err, sql.ErrNoRows) {
			return nil, gerror.Wrap(err, "获取银行卡信息失败")
		}

		if bankIcon.Icon != "" {
			res.BankIcon = bankIcon.Icon
		} else {
			res.BankIcon = "https://imgs.ynz666.com/xiuxianba/2025-04-21/d9c7yhojkjh4sqfjti.png"
		}
	} else if res.WalletStoreBank == nil {
		res.WalletStoreBank = new(entity.WalletStoreBank)
	}

	store := &entity.Store{}
	err = dao.Store.Ctx(ctx).WherePri(req.StoreId).Scan(store)
	if err != nil || errors.Is(err, sql.ErrNoRows) {
		return nil, gerror.Wrap(err, "获取商户信息失败")
	}
	res.Balance = store.Balance

	// 查询总收入
	sum, err := dao.AdminCreditsLog.Ctx(ctx).
		Where(dao.AdminCreditsLog.Columns().CreditType, consts.CreditTypeBalance).
		Where(dao.AdminCreditsLog.Columns().CreditGroup, consts.CreditGroupIncr).
		Where(dao.AdminCreditsLog.Columns().StoreId, req.StoreId).Sum(dao.AdminCreditsLog.Columns().Num)
	if err != nil {
		return
	}
	res.TotalIncome = sum

	conf, err := service.SysConfig().GetConfigByGroup(ctx, &sysin.GetConfigInp{Group: "cash"})
	if err != nil {
		return
	}

	var config *model.CashConfig
	if err = gconv.Struct(conf.List, &config); err != nil {
		return
	}
	res.Fee = config.MinFee

	return
}

func (c *ControllerV1) WalletWithdraw(ctx context.Context, req *v1.WalletWithdrawReq) (res *v1.WalletWithdrawRes, err error) {

	var (
		config      *model.CashConfig // 提现配置
		bankName    string            // 银行名称
		accountNum  string            // 银行账号
		accountName string            // 开户名
		store       *entity.Store     // 商户信息
		storeId     int64             // 商户ID
		name        string            // 提现名
		roleName    string            // 角色名称
	)

	// 获取用户信息
	mb, err := service.AdminMember().GetById(ctx, &adminin.GetByIdInp{
		Id: contexts.GetUserId(ctx),
	})
	if err != nil || mb == nil {
		err = gerror.New("获取用户信息失败")
		return
	}

	// 商户权限验证
	if req.Platform == consts.PlatformStore && req.StoreId != 0 {
		if flag, err := service.SysStoreMember().StorePermission(ctx, &sysin.StorePermissionInp{
			StoreId: req.StoreId,
			IsAdmin: 1,
		}); err != nil {
			return nil, err
		} else if !flag {
			return nil, gerror.New("无商户操作权限")
		}

		// 获取商户信息
		err = dao.Store.Ctx(ctx).WherePri(req.StoreId).Scan(&store)
		if errors.Is(err, sql.ErrNoRows) && mb.RoleId != consts.RoleStore {
			return nil, gerror.Wrap(err, "获取商户信息失败")
		}
	}

	// 获取角色名称
	roleName = consts.GetRoleName(mb.RoleId)

	// 获取提现配置
	conf, err := service.SysConfig().GetConfigByGroup(ctx, &sysin.GetConfigInp{Group: "cash"})
	if err != nil {
		return
	}

	if err = gconv.Struct(conf.List, &config); err != nil {
		return
	}

	if !config.Switch {
		err = gerror.New("提现通道正在升级维护中，请稍后再试！")
		return
	}

	if req.Amount < config.MinMoney {
		err = gerror.Newf("单次提现金额不能低于 %v 元", config.MinMoney)
		return
	}

	// 提现手续费
	fee := config.MinFee

	lastMoney := req.Amount - fee

	if req.Type == consts.WithdrawTypeBank { // 银行卡提现
		if consts.IsUserRole(mb.RoleId) && req.Platform == consts.PlatformUser { // 用户提现
			// 设置提现银行卡信息
			bankName = mb.BankName
			accountNum = mb.AccountNum
			accountName = mb.AccountName
			// 设置用户名
			name = mb.RealName
			if mb.RealName == "" {
				name = mb.Nickname
			}
		} else if store != nil && store.Id > 0 && mb.RoleId == consts.RoleStore && req.Platform == consts.PlatformStore { // 商户提现
			// 商户是否绑定银行卡
			walletStoreBank := &entity.WalletStoreBank{}
			err = dao.WalletStoreBank.Ctx(ctx).Where(g.Map{
				dao.WalletStoreBank.Columns().StoreId: req.StoreId,
			}).Scan(walletStoreBank)
			if errors.Is(err, sql.ErrNoRows) {
				err = gerror.New("请先绑定银行卡")
				return
			} else if err != nil {
				return
			}
			bankName = walletStoreBank.BankName
			accountNum = walletStoreBank.AccountNum
			accountName = walletStoreBank.AccountName
			name = store.Name
			storeId = store.Id
		} else { // 无权限
			return nil, gerror.New("无权限")
		}
		if bankName == "" && accountNum == "" {
			err = gerror.New("请先绑定银行卡")
			return
		}
	} else if req.Type == consts.WithdrawTypeWx { // 微信提现
		if consts.IsUserRole(mb.RoleId) && req.Platform == consts.PlatformUser { // 用户提现

			if req.Amount > 50 { // 不扣除手续费
				lastMoney = req.Amount
				fee = 0
			}

			// 设置用户名
			name = mb.RealName
			if mb.RealName == "" {
				name = mb.Nickname
			}
		} else {
			err = gerror.New("不支持微信提现")
			return
		}
	} else {
		err = gerror.New("提现类型错误")
		return
	}

	err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
		// 添加提现记录
		lastInsertId, err := dao.AdminCash.Ctx(ctx).Data(
			entity.AdminCash{
				MemberId:        contexts.GetUserId(ctx),
				Money:           req.Amount,
				Fee:             fee,
				LastMoney:       lastMoney,
				Ip:              location.GetClientIp(ghttp.RequestFromCtx(ctx)),
				Status:          consts.CashStatusWait,
				Msg:             "",
				MerchantOrderNo: payment.GenOutTradeNo(),
				CreatedAt:       gtime.Now(),
				Mobile:          mb.Mobile,
				WithdrawType:    req.Type,
				StoreId:         storeId,
				BankName:        bankName,
				AccountNum:      accountNum,
				AccountName:     accountName,
			}).InsertAndGetId()
		if err != nil {
			return
		}

		// 更新余额
		_, err = service.AdminCreditsLog().SaveBalance(ctx, &adminin.CreditsLogSaveBalanceInp{
			MemberId:    contexts.GetUserId(ctx),
			StoreId:     storeId,
			AppId:       contexts.GetModule(ctx),
			AddonsName:  contexts.GetAddonName(ctx),
			CreditGroup: consts.CreditGroupApplyCash,
			Num:         -req.Amount,
			MapId:       lastInsertId,
			Remark:      roleName + "：" + name + "，申请提现",
		})
		if err != nil {
			return
		}

		// 发送通知
		err = service.AdminNotice().Send(ctx, &adminin.NoticeSendInp{
			Title:   "提现申请",
			Content: roleName + "：" + name + "，申请提现",
			Status:  1,                       // 已启用
			Type:    consts.NoticeTypeLetter, // 私信
			ReceiverRole: []int64{
				consts.RoleSuper,  // 超级管理员
				consts.RoleManage, // 管理员
			},
		})
		if err != nil {
			return
		}

		return
	})

	if err != nil {
		err = gerror.Wrap(err, "申请提现失败，"+err.Error())
		return
	}

	return
}

func (c *ControllerV1) PaymentNotify(ctx context.Context, req *v1.PaymentNotifyReq) (res *v1.PaymentNotifyRes, err error) {

	// 支付配置
	payConfig := payment.GetConfig()

	// 验签
	var respData bytes.Buffer
	respData.WriteString(strconv.Itoa(req.Status))
	respData.WriteString(req.ErrorCode)
	respData.WriteString(req.ErrorCodeDesc)
	respData.WriteString(req.UserNo)
	respData.WriteString(req.TradeMerchantNo)
	respData.WriteString(req.MerchantOrderNo)
	respData.WriteString(req.PlatformSerialNo)
	respData.WriteString(req.ReceiverAccountNoEnc)
	respData.WriteString(req.ReceiverNameEnc)
	respData.WriteString(fmt.Sprintf("%.2f", req.PaidAmount))
	respData.WriteString(fmt.Sprintf("%.2f", req.Fee))
	signResp := utils.SignByMD5(respData.String(), payConfig.AggJoinPayMerchantKey)
	//logx.Infof("响应结果拼接 --------------------------------->%s", respData.String())
	//logx.Infof("响应结果拼接签名 --------------------------------->%s", signResp)
	//logx.Infof("响应结果拼接签名 --------------------------------->%s", req.Hmac)
	if signResp != strings.ToUpper(req.Hmac) {
		//logx.Info("响应结果验签 --------------------------------->不符合")
		return nil, gerror.New("非法请求")
	}

	// 状态（1.处理中 2.打款中 3.提现异常 4.提现成功）
	var status int64 = 3
	if req.Status == 205 {
		status = 4
	}
	marshal, err := jsonx.Marshal(req)
	if err != nil {
		return nil, err
	}

	var models *entity.AdminCash
	if err = dao.AdminCash.Ctx(ctx).Where(dao.AdminCash.Columns().MerchantOrderNo, req.MerchantOrderNo).Scan(&models); err != nil {
		return
	}

	// 打款未完成，则继续接受回调
	if models.Status == 2 || models.Status == 3 {
		data := g.Map{
			dao.AdminCash.Columns().HandleAt: gtime.Now(),
			dao.AdminCash.Columns().Status:   status,
			dao.AdminCash.Columns().Remark:   string(marshal),
		}
		if status == 3 {
			data[dao.AdminCash.Columns().Msg] = req.ErrorCodeDesc
			data[dao.AdminCash.Columns().ErrMsg] = req.ErrorCode + " - " + req.ErrorCodeDesc
		}

		_, err = dao.AdminCash.Ctx(ctx).Where(dao.AdminCash.Columns().Id, models.Id).Data(data).Update()
		if err != nil {
			return nil, err
		}
	}

	response.RText(g.RequestFromCtx(ctx), "{\"statusCode\":\"2001\",\"message\":\"成功\"}")
	return
}

// 获取钱包变动记录
func (c *ControllerV1) WalletChangeLog(ctx context.Context, req *v1.WalletChangeLogReq) (res *v1.WalletChangeLogRes, err error) {

	// 商户权限验证
	if req.StoreID != 0 {
		if flag, err := service.SysStoreMember().StorePermission(ctx, &sysin.StorePermissionInp{
			StoreId: req.StoreID,
			IsAdmin: 1,
		}); err != nil {
			return nil, err
		} else if !flag {
			return nil, gerror.New("无商户操作权限")
		}
	}

	res = &v1.WalletChangeLogRes{}

	mod := dao.AdminCreditsLog.Ctx(ctx)
	mod = mod.FieldsPrefix(dao.AdminCreditsLog.Table(), adminin.WalletCreditsLogModel{})

	if req.BizType == 1 {
		mod = mod.Fields(`
			CASE
				WHEN hg_admin_cash.withdraw_type = 1 AND hg_admin_cash.status = 1 THEN '处理中'
				WHEN hg_admin_cash.withdraw_type = 1 AND hg_admin_cash.status = 2 THEN '打款中'
				WHEN hg_admin_cash.withdraw_type = 2 AND hg_admin_cash.status = 1 THEN '审核中'
				WHEN hg_admin_cash.withdraw_type = 2 AND hg_admin_cash.status = 2 THEN '审核通过'
				WHEN hg_admin_cash.status = 3 THEN '提现异常'
				WHEN hg_admin_cash.status = 4 THEN '提现成功'
				WHEN hg_admin_cash.status IS NULL THEN ''
				ELSE '未知状态'
			END AS statusName
		`)
		// 关联表字段
		mod = mod.LeftJoinOnFields(dao.AdminCash.Table(), dao.AdminCreditsLog.Columns().MapId, "=", dao.AdminCash.Columns().Id)
	} else if req.BizType == 2 {
		mod = mod.Fields(`
			CASE
    			WHEN hg_order.member_card_id >= 1 AND hg_order.member_card_id <= 3 THEN 1
				WHEN hg_order.member_card_id >= 4 AND hg_order.member_card_id <= 5 THEN 2
				WHEN hg_order.order_type = '团购订单' THEN 3
				ELSE 0
			END AS commissionType
		`)

		mod = mod.Fields(hgorm.JoinFields(ctx, adminin.WalletCreditsLogModel{}, &dao.Order, "order"))
		mod = mod.Fields(hgorm.JoinFields(ctx, adminin.WalletCreditsLogModel{}, &dao.AdminMember, "adminMember"))
		mod = mod.Fields(hgorm.JoinFields(ctx, adminin.WalletCreditsLogModel{}, &dao.Product, "product"))
		mod = mod.Fields(hgorm.JoinFields(ctx, adminin.WalletCreditsLogModel{}, &dao.MemberCard, "memberCard"))
		mod = mod.Fields()

		// 关联表字段
		mod = mod.LeftJoinOnFields(dao.Order.Table(), dao.AdminCreditsLog.Columns().OrderId, "=", dao.Order.Columns().Id)
		mod = mod.LeftJoin(dao.AdminMember.Table(), dao.AdminMember.Table()+"."+dao.AdminMember.Columns().Id+"="+dao.Order.Table()+"."+dao.Order.Columns().UserId)
		mod = mod.LeftJoin(dao.Product.Table(), dao.Order.Table()+"."+dao.Order.Columns().ProductId+"="+dao.Product.Table()+"."+dao.Product.Columns().Id)
		mod = mod.LeftJoin(dao.MemberCard.Table(), dao.Order.Table()+"."+dao.Order.Columns().MemberCardId+"="+dao.MemberCard.Table()+"."+dao.MemberCard.Columns().Id)
	}

	if req.StoreID != 0 { // 商户ID
		mod = mod.Where(dao.AdminCreditsLog.Columns().StoreId, req.StoreID)
	} else { // 用户ID
		mod = mod.Where(dao.AdminCreditsLog.Columns().MemberId, contexts.GetUserId(ctx))
	}
	if req.CreditType != "" { // 变动类型
		mod = mod.Where(dao.AdminCreditsLog.Columns().CreditType, req.CreditType)
	}

	if req.BizType == 1 { // 钱包
		if req.StoreID != 0 {
			mod = mod.WhereIn(dao.AdminCreditsLog.Columns().CreditGroup, consts.GetCreditGroup(req.Type))
		} else {
			mod = mod.WhereIn(dao.AdminCreditsLog.Columns().CreditGroup, consts.GetUserCreditGroup(req.Type))
		}
		// 优先排序：withdraw_type = 2 AND status = 2
		mod = mod.Order(`
			CASE
				WHEN hg_admin_cash.withdraw_type = 2 AND hg_admin_cash.status = 2 THEN 0
				ELSE 1
			END
		`)
	} else if req.BizType == 2 { // 佣金
		mod = mod.Where(dao.AdminCreditsLog.Columns().CreditGroup, consts.CreditGroupDistributionIncr)
	}
	if req.CommissionType != 0 {
		switch req.CommissionType {
		case 1:
			mod = mod.WhereGTE(dao.Order.Table()+"."+dao.Order.Columns().MemberCardId, 1)
			mod = mod.WhereLTE(dao.Order.Table()+"."+dao.Order.Columns().MemberCardId, 3)
		case 2:
			mod = mod.WhereGTE(dao.Order.Table()+"."+dao.Order.Columns().MemberCardId, 4)
			mod = mod.WhereLTE(dao.Order.Table()+"."+dao.Order.Columns().MemberCardId, 5)
		case 3:
			mod = mod.Where(dao.Order.Table()+"."+dao.Order.Columns().OrderType, "团购订单")
		}
	}

	// 查询
	err = mod.Page(req.Page, req.PerPage).
		// 其他记录按时间倒序排列
		OrderDesc(dao.AdminCreditsLog.Columns().CreatedAt).
		ScanAndCount(&res.List, &res.TotalCount, false)
	if err != nil {
		return
	}
	if res.List == nil {
		res.List = []*adminin.WalletCreditsLogModel{}
	} else {
		// 设置加减标记
		for _, v := range res.List {
			for _, v1 := range consts.CreditIncr {
				if v.CreditGroup == v1 {
					v.ChangeFlag = 1
				}
			}
			if v.ChangeFlag == 0 {
				v.ChangeFlag = 2
			}
			if v.MemberCardName != "" {
				v.ProductName = v.MemberCardName
			}
			if v.MemberCardImgUrl != "" {
				v.ProductMainImage = gjson.New([]string{v.MemberCardImgUrl})
			}
		}
	}
	res.PageRes.Pack(req, res.TotalCount)
	return
}

func (c *ControllerV1) WalletWithdrawToWechat(ctx context.Context, req *v1.WalletWithdrawToWechatReq) (res *v1.WalletWithdrawToWechatRes, err error) {

	// 资金变动日志
	adminCreditsLog := entity.AdminCreditsLog{}
	err = dao.AdminCreditsLog.Ctx(ctx).
		WherePri(dao.AdminCreditsLog.Columns().Id, req.WalletCreditsLogID).
		Where(dao.AdminCreditsLog.Columns().MemberId, contexts.GetUserId(ctx)).
		Scan(&adminCreditsLog)
	if err != nil {
		return nil, gerror.New("获取提现信息失败")
	}

	// 提现记录
	adminCash := entity.AdminCash{}
	err = dao.AdminCash.Ctx(ctx).
		WherePri(dao.AdminCash.Columns().Id, adminCreditsLog.MapId).
		Where(dao.AdminCash.Columns().WithdrawType, consts.WithdrawTypeWx). // 提现方式：微信钱包提现
		Where(dao.AdminCash.Columns().Status, 2).                           // 状态：审核通过
		Scan(&adminCash)
	if err != nil {
		return nil, gerror.New("获取提现信息失败")
	}

	res = new(v1.WalletWithdrawToWechatRes)
	res.MchId = payment.GetConfig().WxPayMchId

	// 判断创建时间是否在24小时以内，不在24小时内，则更新商家转账信息
	if adminCash.HandleAt.Add(24 * time.Hour).Before(gtime.Now()) {
		payLog := entity.PayLog{}
		err = dao.PayLog.Ctx(ctx).Where(dao.PayLog.Columns().AdminCashId, adminCash.Id).Scan(&payLog)
		if err != nil {
			return nil, gerror.New("获取提现信息失败")
		}

		payLog.OutTradeNo = payment.GenOutTradeNo()

		resTB, err2 := payment.New(consts.PayTypeWxPay).Transfer(ctx, payin.CreateOrderInp{&payLog})
		if err2 != nil {
			return nil, gerror.New("获取提现信息失败")
		}

		_, err = dao.PayLog.Ctx(ctx).WherePri(payLog.Id).Data(g.Map{
			dao.PayLog.Columns().OutTradeNo: payLog.OutTradeNo,
		}).Update()
		if err != nil {
			return nil, gerror.New("获取提现信息失败")
		}
		_, err = dao.AdminCash.Ctx(ctx).WherePri(adminCash.Id).Data(g.Map{
			dao.AdminCash.Columns().Remark:   gjson.New(resTB).String(),
			dao.AdminCash.Columns().HandleAt: gtime.Now(),
		}).Update()
		if err != nil {
			return nil, gerror.New("获取提现信息失败")
		}
		err = gjson.New(resTB).Scan(&res.WalletWithdrawToWechatModel)
		if err != nil {
			return nil, gerror.New("获取提现信息失败")
		}
		return
	} else {
		err = gjson.New(adminCash.Remark).Scan(&res.WalletWithdrawToWechatModel)
		if err != nil {
			return nil, gerror.New("获取提现信息失败")
		}
		return
	}
}

func (c *ControllerV1) WalletCommissionStat(ctx context.Context, req *v1.WalletCommissionStatReq) (res *v1.WalletCommissionStatRes, err error) {

	userId := contexts.GetUserId(ctx)

	// 获取数据
	err = g.DB().Raw(fmt.Sprintf(`
	SELECT 
	
		-- 总佣金
		(
			SELECT SUM(num) FROM hg_admin_credits_log 
			WHERE member_id = %d AND credit_group = 'distribution_incr'
		) AS total_commission,

		-- 售卡总收益
		(
			SELECT SUM(num) FROM hg_admin_credits_log 
			LEFT JOIN hg_order ON hg_admin_credits_log.order_id = hg_order.id 
			WHERE 
			    hg_admin_credits_log.member_id = %d AND hg_admin_credits_log.credit_group = 'distribution_incr'
			    AND hg_order.member_card_id >= 1 AND hg_order.member_card_id <= 3
		) AS total_sale_commission,
	
		-- 礼包总收益
		(
			SELECT SUM(num) FROM hg_admin_credits_log 
			LEFT JOIN hg_order ON hg_admin_credits_log.order_id = hg_order.id 
			WHERE 
			    hg_admin_credits_log.member_id = %d AND hg_admin_credits_log.credit_group = 'distribution_incr'
			    AND hg_order.member_card_id >= 4 AND hg_order.member_card_id <= 5
		) AS total_gift_commission,
	    
	    -- 团购总收益
	    (
	        SELECT SUM(num) FROM hg_admin_credits_log 
			LEFT JOIN hg_order ON hg_admin_credits_log.order_id = hg_order.id 
			WHERE 
			    hg_admin_credits_log.member_id = %d AND hg_admin_credits_log.credit_group = 'distribution_incr'
			    AND hg_order.order_type = '团购订单'
	    ) AS total_group_commission,
	
		-- 今日收益
		(
			SELECT SUM(num) FROM hg_admin_credits_log 
			WHERE member_id = %d AND credit_group = 'distribution_incr' AND created_at >= DATE_FORMAT(NOW(),'%%Y-%%m-%%d 00:00:00')
		) AS today_commission,
	    
	    -- 售卡今日收益
		(
			SELECT SUM(num) FROM hg_admin_credits_log 
			LEFT JOIN hg_order ON hg_admin_credits_log.order_id = hg_order.id 
			WHERE 
			    hg_admin_credits_log.member_id = %d AND hg_admin_credits_log.credit_group = 'distribution_incr'
			    AND hg_order.member_card_id >= 1 AND hg_order.member_card_id <= 3 AND hg_admin_credits_log.created_at >= DATE_FORMAT(NOW(),'%%Y-%%m-%%d 00:00:00')
		) AS today_sale_commission,

		-- 礼包今日收益
		(
			SELECT SUM(num) FROM hg_admin_credits_log 
			LEFT JOIN hg_order ON hg_admin_credits_log.order_id = hg_order.id 
			WHERE 
			    hg_admin_credits_log.member_id = %d AND hg_admin_credits_log.credit_group = 'distribution_incr'
			    AND hg_order.member_card_id >= 4 AND hg_order.member_card_id <= 5 AND hg_admin_credits_log.created_at >= DATE_FORMAT(NOW(),'%%Y-%%m-%%d 00:00:00')
		) AS today_gift_commission,
	    
	    -- 团购今日收益
	    (
	        SELECT SUM(num) FROM hg_admin_credits_log 
			LEFT JOIN hg_order ON hg_admin_credits_log.order_id = hg_order.id 
			WHERE 
			    hg_admin_credits_log.member_id = %d AND hg_admin_credits_log.credit_group = 'distribution_incr'
			    AND hg_order.order_type = '团购订单' AND hg_admin_credits_log.created_at >= DATE_FORMAT(NOW(),'%%Y-%%m-%%d 00:00:00')
	    ) AS today_group_commission
	
	`, userId, userId, userId, userId, userId, userId, userId, userId)).Scan(&res)
	return
}
